package com.zwj.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.zwj.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

@Api(value = "登录接口")
@Controller
public class KaptchaController {
    @Resource
    DefaultKaptcha kaptcha;
    @ApiOperation(value = "请求验证码")
    @GetMapping("/getKaptcha")
    public void getKaptcha(HttpServletRequest request, HttpServletResponse response,String id) throws IOException {
        byte[] b;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            // 生产验证码并保存到session中
            String createText = kaptcha.createText();
            request.getSession().setAttribute(id, createText);
            request.getSession().setMaxInactiveInterval(60);
            // 使用生成的验证码返回一个BufferedImage对象并写入到字节数组流outputStream中
            BufferedImage image = kaptcha.createImage(createText);
            ImageIO.write(image, "jpg", outputStream);
        } catch (Exception e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        b = outputStream.toByteArray();
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream stream = response.getOutputStream();
        stream.write(b);
        stream.flush();
        stream.close();
    }
    @ResponseBody
    @ApiOperation(value = "请求验证码id")
    @GetMapping("/getCodeId")
    public Result codeId(){
        Random r = new Random();
        int a = r.nextInt(10000000);
        System.out.println(a);
        return Result.success(a);
    }
//    @ApiOperation(value = "验证码验证")
//    @ResponseBody
//    @GetMapping("/checkKaptcha")
//    public String checkKaptcha(HttpServletRequest request,String code) {
//        String rightCode = (String) request.getSession().getAttribute("rightCode");
////        String inputCode = request.getParameter("inputCode");
//        String inputCode = code;
////        System.out.println(rightCode);
////        System.out.println(inputCode);
//        if (!rightCode.equalsIgnoreCase(inputCode)) {
//            System.out.println("验证码输入错误！");
//            return "验证码输入错误！";
//        }
//        System.out.println("验证码输入正确！");
//        return "验证码输入正确！";
//    }

}

